<template>
  <div class="user_bxo">
    <!-- 面包屑 -->
    <MBX level1="用户管理" level2="用户列表"></MBX><br />

    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 搜索框 -->
        <el-col :span="12">
          <el-input
            clearable
            placeholder="请输入内容"
            class="input-with-select"
            v-model="usersFrom.query"
            @input="searchBtn"
          >
            <el-button
              @click="searchBtn"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="6">
          <el-button type="primary" @click="userBtn">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table :data="usersData" class="mt16" border style="width: 100%">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 状态 -->
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <div>
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="Switch(scope.row)"
              >
              </el-switch>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column prop="" label="操作" width="250px">
          <template slot-scope="scope">
            <div>
              <!-- 编辑 -->
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="edit(scope.row)"
              ></el-button>
              <!-- 删除 -->
              <el-button
                size="mini"
                type="danger"
                @click="del(scope.row)"
                icon="el-icon-delete"
              ></el-button>
              <!-- 分配角色  -->
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="SetRole(scope.row)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="block mt16">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="usersFrom.pagenum"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="usersFrom.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- -- 添加用户对话框 弹出框 :rules="rules" -->
    <el-dialog title="添加用户" :visible.sync="addBox">
      <el-form
        title="添加用户"
        ref="addForm"
        label-width="100px"
        :rules="rules"
        :model="userAddList"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userAddList.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userAddList.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userAddList.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userAddList.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addBox = false">取 消</el-button>
        <el-button type="primary" @click="yesAdd(userAddList)">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 【编辑】 用户对话框 弹出框 -->
    <el-dialog title="编辑用户" :visible.sync="editBox">
      <!--  中间掺入输入框 -->
      <el-form
        title="编辑用户"
        :rules="rules"
        ref="editForm"
        :model="userAddList"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userAddList.username"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userAddList.email"></el-input>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userAddList.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editBox = false">取 消</el-button>
        <el-button type="primary" @click="editUserOk(userAddList)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 【分配角色弹出框】 -->
    <el-dialog title="分配角色" :visible.sync="isSetRole">
      <el-form :model="setRoleFrom">
        <div class="txt">
          <p>当前用户：{{ currentUser.username }}</p>
          <p>当前角色：{{ currentUser.role_name }}</p>
        </div>
        <el-form-item label="分配新角色">
          <!-- <p>{{setRoleFrom.currentRoleId}}</p> -->
          <el-select v-model="setRoleFrom.currentRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isSetRole = false">取 消</el-button>
        <el-button type="primary" @click="setRoleToUserOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { usersApi, userDelApi } from "../../../http/api";
import _ from "lodash";
export default {
  data() {
    // 验证邮箱
    const checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则
      //     以大写字母或数字    \w 可以是数字字母下划线  + 就表示他前面的那个，是一个，或者一个以上
      const reg = /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/;

      // 如果 不符合reg
      if (!reg.test(value)) {
        return callback(new Error("您输入的邮箱不合法，请检查"));
      }
      callback();
    };
    // 验证手机号
    const checkMobile = (rule, value, callback) => {
      const reg = /1[3456789]\d{9}$/;
      if (!reg.test(value)) {
        return callback(new Error("您输入的电话号不合法，请检查"));
      }
      callback();
    };
    return {
      value: true, // 状态的
      total: 0,
      //搜索的数据
      usersFrom: {
        query: "",
        pagenum: 1, // 当前页码
        pagesize: 5, //每页显示条数
      },
      usersData: [], // 用户数据
      // 用户的数据
      userAddList: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addBox: false, // 添加的弹出框状态
      // 添加用户校验
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "输入的用户长度必须5~20之间",
            trigger: "blur",
          },
        ],

        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],

        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],

        mobile: [
          { required: true, message: "请输入电话号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editBox: false, //   编辑弹出框的状态
      isSetRole: false, // 分配角色弹出框的状态
      setRoleFrom: {}, // 分配角色的数据
      rolesList: [], // 请求过来的角色列表
      currentUser: {},
    };
  },
  methods: {
    //   点击分配角色按钮
    async SetRole(user) {
      // console.log(user);
      this.currentUser = user;
      this.isSetRole = true; // 打开弹窗
      const res = await this.$API.getUserRolesListApi();
      // console.log("請求點擊打開分配id", res);
      this.rolesList = res;
    },
    // 分配角色的弹出框确定按钮
    async setRoleToUserOk() {
      const { id } = this.currentUser;
      //   console.log("分配角色", id);
      const { currentRoleId } = this.setRoleFrom;
      // console.log(currentRoleId);
      const res = await this.$API.userRoleApi(id, currentRoleId);
      // setUserRolesApi
      this.isSetRole = false;
      this.usersList();
    },

    //   点击编辑按钮，弹出弹出框
    edit(row) {
      // console.log("编辑的这一行数据：", row);
      this.userAddList = row;
      this.editBox = true;
    },
    // 点击编辑的确定按钮
    editUserOk() {
      const { id, mobile, email } = this.userAddList;
      const res = this.$API.userEditApi(id, { mobile, email });
      this.usersList();
      this.editBox = false;
    },
    //   点击更改状态
    Switch(row) {
      //   console.log(row);
      const uId = row.id;
      const type = row.mg_state;
      const res = this.$API.userSwitchApi(uId, type);
    },
    //   点击删除按钮
    del(row) {
      // console.log("要删除的一行：", row.id);
      this.$confirm("是否要删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await userDelApi(Number(row.id));
          //   console.log("删除：", res);
          this.usersList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //   点击添加 弹出 弹出框框
    userBtn() {
      // 清空表单数据  优化添加
      this.userAddList = {};
      this.addBox = true;
    },
    // 点击弹出框的确定按钮
    yesAdd() {
      this.$refs.addForm.validate((valid) => {
        if (!valid) return false;
        const res = this.$API.userAddApi(this.userAddList);
        // console.log("添加用户:", res);
        this.addBox = false;
        this.usersList();
      });
    },

    // =====================
    // 搜索用户
    // searchUser() {
    //   console.log("搜索框：", this.queryInfo);
    //   this.usersList();
    // },

    // 搜索  优化 【防抖】处理     //.debounce 防抖工具函数   //function() 立即调用函数
    searchBtn: _.debounce(function () {
      this.usersList();
    }, 1000),

    // 搜索用户  优化 【节流】处理     //.debounce 防抖工具函数   //function() 立即调用函数
    // searchBtn: _.throttle(function() {
    //   this.usersList();
    // }, 1000),
    // ====================

    //   分页
    handleSizeChange(val) {
      this.usersFrom.pagesize = val;
      this.usersList();
    },
    handleCurrentChange(val) {
      this.usersFrom.pagenum = val;
      this.usersList();
    },
    // 请求列表数据
    async usersList() {
      const res = await usersApi(this.usersFrom);
      const { total, users } = res;
      //   console.log("列表数据:", res);
      this.usersData = users;
      this.total = total;
    },
  },
  created() {
    this.usersList();
    this.searchBtn();
  },
};
</script>

<style lang="scss" scoped>
// 卡片
.el-card {
  padding: 0;
  .el-col-8 {
    padding: 0;
    margin: 0;
    height: 40px;
  }
}
</style>
